from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.db.models import Count
from django.shortcuts import render
from django.utils import timezone


class Category(models.Model):
    """图书分类"""
    name = models.CharField("分类名称", max_length=50, unique=True)
    description = models.TextField("分类描述", blank=True, null=True)
    color = models.CharField("分类颜色", max_length=7, default="#007bff", help_text="十六进制颜色代码")

    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = "图书分类"
        verbose_name_plural = verbose_name

class Author(models.Model):
    name = models.CharField("姓名", max_length=100, unique=True)
    biography = models.TextField("生平简介", blank=True, null=True)
    birth_date = models.DateField("出生日期", null=True, blank=True)
    nationality = models.CharField("国籍", max_length=50, blank=True, null=True)
    photo = models.ImageField("作者照片", upload_to='authors/', blank=True, null=True)
    created_at = models.DateTimeField("创建时间", auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "作者"
        verbose_name_plural = verbose_name

class Publisher(models.Model):
    """出版社"""
    name = models.CharField("出版社名称", max_length=100, unique=True)
    address = models.TextField("地址", blank=True, null=True)
    phone = models.CharField("联系电话", max_length=20, blank=True, null=True)
    website = models.URLField("网站", blank=True, null=True)
    
    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = "出版社"
        verbose_name_plural = verbose_name

class Book(models.Model):
    title = models.CharField('书名', max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books', verbose_name="作者")
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="分类")
    publisher = models.ForeignKey(Publisher, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="出版社")
    isbn = models.CharField('ISBN', max_length=13, unique=True)
    publish_date = models.DateField('出版日期')
    quantity = models.PositiveIntegerField('库存数量', default=1)
    total_quantity = models.PositiveIntegerField('总数量', default=1, help_text="包括借出的数量")
    summary = models.TextField('摘要', null=True, blank=True)
    average_rating = models.FloatField('平均评分', default=0)
    cover_image = models.ImageField('封面图片', upload_to='book_covers/', blank=True, null=True)
    language = models.CharField('语言', max_length=20, default='中文')
    pages = models.PositiveIntegerField('页数', null=True, blank=True)
    price = models.DecimalField('价格', max_digits=8, decimal_places=2, null=True, blank=True)
    location = models.CharField('馆藏位置', max_length=50, blank=True, null=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    # 统计字段
    borrow_count = models.PositiveIntegerField('借阅次数', default=0)
    view_count = models.PositiveIntegerField('浏览次数', default=0)

    def __str__(self):
        return f"{self.title} ({self.author.name})"

    def update_rating(self):
        """计算并更新书籍的平均分"""
        reviews = self.reviews.all()
        if reviews.exists():
            total_rating = sum([review.rating for review in reviews])
            self.average_rating = round(total_rating / reviews.count(), 2)
        else:
            self.average_rating = 0
        self.save()
    
    def is_available(self):
        """检查图书是否可借"""
        return self.quantity > 0
    
    def get_borrowed_quantity(self):
        """获取已借出数量"""
        return self.total_quantity - self.quantity
    
    def increment_view_count(self):
        """增加浏览次数"""
        self.view_count += 1
        self.save(update_fields=['view_count'])

class BorrowRecord(models.Model):
    STATUS_CHOICES = [
        ('borrowed', '已借出'),
        ('returned', '已归还'),
        ('overdue', '已逾期'),
    ]
    
    book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name="书籍")
    borrower = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="借阅人")
    borrow_date = models.DateTimeField("借阅日期", auto_now_add=True)
    return_date = models.DateTimeField("归还日期", null=True, blank=True)
    due_date = models.DateField("应归还日期")
    renewals_left = models.PositiveSmallIntegerField("剩余续借次数", default=1)
    status = models.CharField("状态", max_length=10, choices=STATUS_CHOICES, default='borrowed')
    notes = models.TextField("备注", blank=True, null=True)

    def __str__(self):
        return f"{self.borrower.username} 借阅了《{self.book.title}》"

    def save(self, *args, **kwargs):
        # 自动更新状态
        if self.return_date:
            self.status = 'returned'
        elif self.due_date < timezone.now().date():
            self.status = 'overdue'
        else:
            self.status = 'borrowed'
        super().save(*args, **kwargs)
    
    def is_overdue(self):
        """检查是否逾期"""
        return self.due_date < timezone.now().date() and not self.return_date
    
    def get_days_overdue(self):
        """获取逾期天数"""
        if self.is_overdue():
            return (timezone.now().date() - self.due_date).days
        return 0

    class Meta:
        verbose_name = "借阅记录"
        verbose_name_plural = verbose_name

class Review(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews', verbose_name="书籍")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="评论用户")
    rating = models.PositiveSmallIntegerField(
        '评分',
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )
    comment = models.TextField('评论', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    helpful_count = models.PositiveIntegerField('有用数', default=0)

    class Meta:
        # 确保每个用户对一本书只能评论一次
        unique_together = ('book', 'user')
        ordering = ['-created_at']
        verbose_name = "评论"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.user.username} - {self.book.title} ({self.rating} 星)"

class UserProfile(models.Model):
    """用户档案"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    phone = models.CharField('手机号', max_length=20, blank=True, null=True)
    address = models.TextField('地址', blank=True, null=True)
    student_id = models.CharField('学号/工号', max_length=20, blank=True, null=True)
    department = models.CharField('院系/部门', max_length=100, blank=True, null=True)
    avatar = models.ImageField('头像', upload_to='avatars/', blank=True, null=True)
    max_borrow_limit = models.PositiveIntegerField('最大借阅数量', default=5)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    def __str__(self):
        return f"{self.user.username} 的档案"
    
    def get_current_borrowed_count(self):
        """获取当前借阅数量"""
        return BorrowRecord.objects.filter(
            borrower=self.user, 
            return_date__isnull=True
        ).count()
    
    def can_borrow_more(self):
        """检查是否可以继续借书"""
        return self.get_current_borrowed_count() < self.max_borrow_limit

class Notification(models.Model):
    """通知消息"""
    TYPE_CHOICES = [
        ('overdue', '逾期提醒'),
        ('due_soon', '即将到期'),
        ('return_reminder', '归还提醒'),
        ('system', '系统通知'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    title = models.CharField('标题', max_length=200)
    message = models.TextField('消息内容')
    notification_type = models.CharField('类型', max_length=20, choices=TYPE_CHOICES)
    is_read = models.BooleanField('已读', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    related_book = models.ForeignKey(Book, on_delete=models.CASCADE, null=True, blank=True, verbose_name="相关图书")
    
    class Meta:
        ordering = ['-created_at']
        verbose_name = "通知"
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return f"{self.user.username} - {self.title}"
class YourModel(models.Model):
    name = models.CharField(max_length=100)
    color = models.CharField(max_length=50)
    description = models.TextField()
    num_books = models.IntegerField(default=0)


def statistics_view(request):
    # 使用annotate动态创建num_books字段
    queryset = YourModel.objects.annotate(
        num_books=Count('book')  # 使用你的实际关联字段名
    )

    # 现在可以安全地使用num_books进行过滤或排序
    # queryset = queryset.order_by('-num_books')

    context = {'data': queryset}
    return render(request, 'your_template.html', context)


def statistics_view(request):
    # 使用annotate动态创建num_books字段
    queryset = YourModel.objects.annotate(
        num_books=Count('book')  # 使用你的实际关联字段名
    )

    # 现在可以安全地使用num_books进行过滤或排序
    # queryset = queryset.order_by('-num_books')

    context = {'data': queryset}
    return render(request, 'your_template.html', context)